using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections.Generic;
using System.Threading;
using static UnityEngine.GraphicsBuffer;
using System.Collections;

public class NetworkManager : MonoBehaviour
{
    public int port = 8888;
    public string serverIP = "127.0.0.1";
    public GameObject playerPrefab;
    public GameObject bulletPrefab;

    // 颜色设置
    public Color serverPlayerColor = Color.green;  // 服务器玩家颜色
    public Color clientPlayerColor = Color.blue;   // 客户端玩家颜色
    public Color otherPlayerColor = Color.red;     // 其他玩家颜色

    // 网络状态
    private Socket socket;
    public bool isServer = false;
    private bool isConnected = false;
    private Thread receiveThread;
    private Dictionary<string, GameObject> players = new Dictionary<string, GameObject>();
    private Dictionary<string, IPEndPoint> clientEndPoints = new Dictionary<string, IPEndPoint>();
    private string myId;

    // UI状态
    private string statusMessage = "";
    private List<string> connectedPlayers = new List<string>();
    private bool showDisconnectButton = false;
    private bool showQuitButton = true;
    public GameObject healthUIPrefab;  // 在Inspector中设置
    private CameraFollow cf;

    // 游戏管理器引用
    private GameManager gameManager;

    // 网络消息结构
    [Serializable]
    public class NetworkMessage
    {
        public string id;
        public string type;  // join, move, color, disconnect, shoot, hit, health, game_start, game_end, score_update, team_assign
        public float posX;
        public float posY;
        public float posZ;
        public float colorR;
        public float colorG;
        public float colorB;
        public string data;  // 额外数据字段，用于扩展
        public float rotY; // 新增：玩家Y轴旋转角度
        public float health; // 新增：玩家血量同步

        // 炮弹相关字段
        public string targetId;    // 目标ID
        public float damage;       // 伤害值
        public float dirX;         // 方向X
        public float dirY;         // 方向Y
        public float dirZ;         // 方向Z
    }

    void Start()
    {
        // 获取游戏管理器引用
        gameManager = FindObjectOfType<GameManager>();
        if (gameManager == null)
        {
            Debug.LogError("未找到GameManager！请确保场景中有GameManager对象。");
        }
    }

    void OnGUI()
    {
        GUILayout.BeginArea(new Rect(10, 10, 300, 500));

        // 状态信息显示
        GUILayout.Label("状态: " + statusMessage);

        if (!isConnected)
        {
            // 服务器控制
            if (GUILayout.Button("启动服务器", GUILayout.Width(150), GUILayout.Height(30)))
            {
                StartServer();
            }

            GUILayout.Label("服务器IP:");
            serverIP = GUILayout.TextField(serverIP, GUILayout.Width(150));

            if (GUILayout.Button("连接服务器", GUILayout.Width(150), GUILayout.Height(30)))
            {
                ConnectToServer();
            }
        }
        else
        {
            // 连接后控制
            if (showDisconnectButton)
            {
                if (GUILayout.Button("断开连接", GUILayout.Width(150), GUILayout.Height(30)))
                {
                    DisconnectFromServer();
                }
            }

            // 玩家列表
            GUILayout.Label("已连接玩家:");
            foreach (string player in connectedPlayers)
            {
                GUILayout.Label("- " + player);
            }
        }

        // 退出按钮始终显示
        if (showQuitButton)
        {
            if (GUILayout.Button("退出游戏", GUILayout.Width(150), GUILayout.Height(30)))
            {
                QuitGame();
            }
        }

        GUILayout.EndArea();
    }

    // 启动服务器
    public void StartServer()
    {
        try
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            // 允许地址重用
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            // 使用Any，监听所有网络接口
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, port);
            socket.Bind(ipep);

            isServer = true;
            isConnected = true;
            myId = "Server";
            statusMessage = "服务器已启动，端口: " + port;
            showDisconnectButton = true;

            // 添加自己到玩家列表
            connectedPlayers.Add(myId);

            // 分配服务器玩家到队伍
            string team = gameManager.AssignPlayerTeam(myId);
            Color teamColor = gameManager.GetTeamColor(team);

            // 生成服务器玩家
            SpawnPlayer(myId, teamColor);

            Debug.Log("服务器已启动，端口: " + port);

            // 启动接收线程
            receiveThread = new Thread(new ThreadStart(ReceiveData));
            receiveThread.IsBackground = true;
            receiveThread.Start();
        }
        catch (Exception e)
        {
            statusMessage = "启动服务器错误: " + e.Message;
            Debug.LogError("启动服务器错误: " + e.Message);
        }
    }

    // 连接到服务器
    public void ConnectToServer()
    {
        try
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            // 客户端不需要绑定特定端口，让系统自动分配
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 0);
            socket.Bind(localEndPoint);

            isServer = false;
            isConnected = true;
            myId = "Client_" + UnityEngine.Random.Range(1000, 9999);
            statusMessage = "正在连接到服务器: " + serverIP;
            showDisconnectButton = true;

            // 添加自己到玩家列表
            connectedPlayers.Add(myId);

            // 生成自己的玩家（颜色稍后由服务端分配）
            SpawnPlayer(myId, clientPlayerColor);

            // 发送加入消息给服务器
            NetworkMessage joinMsg = new NetworkMessage
            {
                id = myId,
                type = "join",
                posX = 0,
                posY = 0.5f,
                posZ = 0,
                colorR = clientPlayerColor.r,
                colorG = clientPlayerColor.g,
                colorB = clientPlayerColor.b
            };
            SendMessage(joinMsg);

            Debug.Log("已连接到服务器: " + serverIP);
            statusMessage = "已连接到服务器: " + serverIP;

            // 启动接收线程
            receiveThread = new Thread(new ThreadStart(ReceiveData));
            receiveThread.IsBackground = true;
            receiveThread.Start();
        }
        catch (Exception e)
        {
            statusMessage = "连接服务器错误: " + e.Message;
            Debug.LogError("连接服务器错误: " + e.Message);
        }
    }

    // 断开连接
    public void DisconnectFromServer()
    {
        if (!isConnected) return;

        // 发送断开连接消息
        NetworkMessage disconnectMsg = new NetworkMessage
        {
            id = myId,
            type = "disconnect"
        };

        SendMessage(disconnectMsg);

        // 清理网络
        CleanupNetwork();

        // 清理游戏对象
        foreach (var player in players)
        {
            if (player.Value != null)
            {
                Destroy(player.Value);
            }
        }

        players.Clear();
        clientEndPoints.Clear();
        connectedPlayers.Clear();

        isConnected = false;
        showDisconnectButton = false;
        statusMessage = "已断开连接";
    }

    // 退出游戏
    public void QuitGame()
    {
        DisconnectFromServer();

        // 延迟一秒再退出，确保断开消息有时间发送
        StartCoroutine(DelayedQuit());
    }

    System.Collections.IEnumerator DelayedQuit()
    {
        yield return new WaitForSeconds(1);

#if UNITY_EDITOR
        UnityEditor.EditorApplication.isPlaying = false;
#else
        Application.Quit();
#endif
    }

    // 清理网络资源
    private void CleanupNetwork()
    {
        if (receiveThread != null)
        {
            receiveThread.Abort();
            receiveThread = null;
        }

        if (socket != null)
        {
            socket.Close();
            socket = null;
        }
    }

    // 生成玩家
    private void SpawnPlayer(string id, Color playerColor, Vector3 position = default)
    {
        if (playerPrefab == null)
        {
            Debug.LogError("playerPrefab未设置！请在Inspector中设置预制体引用。");
            return;
        }

        // 如果没有指定位置，使用默认位置
        if (position == default)
        {
            position = new Vector3(-3f, 2.0f, 0);
        }

        GameObject playerObj = Instantiate(playerPrefab, position, Quaternion.identity);
        playerObj.transform.rotation = Quaternion.Euler(-90, 0, 0);
        playerObj.name = id;

        // 本地玩家标记
        bool isLocalPlayer = (id == myId);

        // 设置颜色和控制器
        Renderer renderer = playerObj.GetComponent<Renderer>();
        if (renderer != null)
        {
            renderer.material.color = playerColor;
        }

        PlayerController controller = playerObj.GetComponent<PlayerController>();
        if (controller != null)
        {
            controller.isLocalPlayer = isLocalPlayer;
            controller.playerId = id;

            // 如果有队伍信息，设置队伍
            if (gameManager != null)
            {
                string team = gameManager.GetPlayerTeam(id);
                if (!string.IsNullOrEmpty(team))
                {
                    controller.team = team;
                }
            }

            // 延迟设置子弹发射点（等待坦克模型完全初始化）
            StartCoroutine(SetupBulletSpawnPointDelayed(controller, playerObj));
        }

        // 添加UI
        if (healthUIPrefab != null)
        {
            GameObject ui = Instantiate(healthUIPrefab,
                                      playerObj.transform.position,
                                      Quaternion.identity);
            HealthUI healthUI = ui.GetComponent<HealthUI>();
            if (healthUI != null)
            {
                healthUI.player = controller;
                healthUI.nameText.text = id;
            }
        }

        // 保存到字典
        players.Add(id, playerObj);

        // 设置摄像机跟随
        if (isLocalPlayer)
        {
            StartCoroutine(SetupCameraFollowDelayed(playerObj));
        }

    }

    IEnumerator SetupCameraFollowDelayed(GameObject playerObj)
    {
        // 等待一帧确保CameraFollow的Start方法已执行
        yield return null;

        cf = GameObject.Find("Main Camera").GetComponent<CameraFollow>();
        if (cf != null)
        {
            cf.target = playerObj.transform;
            cf.isLocalPlayer = true; // 确保标记为本地玩家
            cf.SetCamera();
            cf.Initialized();
        }
        else
        {
            Debug.LogError("未找到CameraFollow组件！");
        }
    }

    IEnumerator SetupBulletSpawnPointDelayed(PlayerController controller, GameObject Tank)
    {
        // 等待一帧确保所有组件初始化完成
        yield return null;

        // 查找坦克的炮管或炮塔作为发射点父对象
        Transform turret1 = Tank.transform.Find("GunBarrel"); // 根据实际命名调整
        Transform turret = turret1.Find("GameObject");
        if (turret == null)
        {
            turret = controller.transform; // 如果找不到炮塔，使用玩家根对象
            Debug.LogWarning("未找到炮塔，使用玩家根对象作为发射点父对象");
        }

        // 创建子弹发射点并设置位置
        GameObject spawnPoint = new GameObject("BulletSpawnPoint");
        spawnPoint.transform.SetParent(turret);
        spawnPoint.transform.localPosition = new Vector3(0, 1f, 0); // 调整到炮口位置
        spawnPoint.transform.localRotation = Quaternion.identity;  // 保持与父对象相同的旋转

        // 赋值给控制器
        controller.bulletSpawnPoint = spawnPoint;
    }

    private void SpawnBullet(string shooterId, Vector3 position, Vector3 direction)
    {
        // 假设bulletPrefab已在Inspector中设置
        if (bulletPrefab != null)
        {
            GameObject bullet = Instantiate(bulletPrefab, position, Quaternion.identity);
            Bullet bulletScript = bullet.GetComponent<Bullet>();
            if (bulletScript != null)
            {
                // 获取射击者队伍信息
                string team = null;
                if (gameManager != null)
                {
                    team = gameManager.GetPlayerTeam(shooterId);
                }

                // 设置射击者ID和队伍
                bulletScript.SetShooterInfo(shooterId, team);
                bulletScript.SetDirection(direction);
            }
        }
    }


    // 接收数据
    private void ReceiveData()
    {
        try
        {
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint remote = (EndPoint)sender;

            while (isConnected)
            {
                byte[] data = new byte[1024];
                int recv = 0;

                try
                {
                    recv = socket.ReceiveFrom(data, ref remote);
                }
                catch (SocketException se)
                {
                    // 忽略中断异常 (在关闭socket时可能发生)
                    if (se.ErrorCode == 10004)
                        break;

                    Debug.LogError("接收Socket错误: " + se.Message);
                    continue;
                }

                if (recv > 0)
                {
                    string json = Encoding.ASCII.GetString(data, 0, recv);
                    ProcessMessage(json, remote);
                }
            }
        }
        catch (ThreadAbortException)
        {
            // 线程被中止，正常退出
            Debug.Log("接收线程已终止");
        }
        catch (Exception e)
        {
            Debug.LogError("接收数据错误: " + e.Message);
        }
    }

    // 处理收到的消息
    private void ProcessMessage(string json, EndPoint remote)
    {
        try
        {
            NetworkMessage msg = JsonUtility.FromJson<NetworkMessage>(json);

            // 更新或保存客户端地址
            if (!clientEndPoints.ContainsKey(msg.id))
            {
                clientEndPoints[msg.id] = (IPEndPoint)remote;
                Debug.Log($"新客户端连接: {msg.id} 地址: {remote}");
            }

            // 在主线程中处理
            UnityMainThreadDispatcher.Instance().Enqueue(() => {
                switch (msg.type)
                {
                    case "join":
                        HandleJoinMessage(msg, remote);
                        break;

                    case "move":
                        HandleMoveMessage(msg);
                        break;

                    case "disconnect":
                        HandleDisconnectMessage(msg);
                        break;

                    case "color":
                        HandleColorMessage(msg);
                        break;

                    case "shoot":
                        HandleShootMessage(msg);
                        break;

                    case "hit":
                        HandleHitMessage(msg);
                        break;

                    case "health":
                        HandleHealthMessage(msg);
                        break;

                    case "team_assign":
                        HandleTeamAssignMessage(msg);
                        break;

                    case "game_start":
                        HandleGameStartMessage(msg);
                        break;

                    case "game_end":
                        HandleGameEndMessage(msg);
                        break;

                    case "score_update":
                        HandleScoreUpdateMessage(msg);
                        break;

                    default:
                        Debug.LogWarning("未知消息类型: " + msg.type);
                        break;
                }
            });
        }
        catch (Exception e)
        {
            Debug.LogError("处理消息错误: " + e.Message);
        }
    }

    // 处理加入消息
    private void HandleJoinMessage(NetworkMessage msg, EndPoint remote)
    {
        if (players.ContainsKey(msg.id)) return; // 已存在，忽略

        Debug.Log($"玩家加入: {msg.id}");

        // 记录客户端端点
        if (isServer && remote is IPEndPoint)
        {
            clientEndPoints[msg.id] = (IPEndPoint)remote;

            // 将现有玩家信息发送给新加入的客户端
            foreach (var player in players)
            {
                if (player.Key != msg.id) // 不发送自己
                {
                    PlayerController pc = player.Value.GetComponent<PlayerController>();
                    if (pc != null)
                    {
                        // 发送位置
                        NetworkMessage posMsg = new NetworkMessage
                        {
                            id = player.Key,
                            type = "move",
                            posX = player.Value.transform.position.x,
                            posY = player.Value.transform.position.y,
                            posZ = player.Value.transform.position.z,
                            rotY = player.Value.transform.eulerAngles.y
                        };
                        SendMessageTo(posMsg, remote);

                        // 发送颜色（队伍）
                        Renderer renderer = player.Value.GetComponent<Renderer>();
                        if (renderer != null)
                        {
                            NetworkMessage colorMsg = new NetworkMessage
                            {
                                id = player.Key,
                                type = "color",
                                colorR = renderer.material.color.r,
                                colorG = renderer.material.color.g,
                                colorB = renderer.material.color.b
                            };
                            SendMessageTo(colorMsg, remote);
                        }

                        // 发送血量
                        NetworkMessage healthMsg = new NetworkMessage
                        {
                            id = player.Key,
                            type = "health",
                            health = pc.health
                        };
                        SendMessageTo(healthMsg, remote);
                    }
                }
            }

            // 服务器为新玩家分配队伍
            string team = gameManager.AssignPlayerTeam(msg.id);
            Color teamColor = gameManager.GetTeamColor(team);

            // 发送队伍分配消息
            NetworkMessage teamMsg = new NetworkMessage
            {
                id = msg.id,
                type = "team_assign",
                data = team,
                colorR = teamColor.r,
                colorG = teamColor.g,
                colorB = teamColor.b
            };

            // 广播给所有人（包括新玩家）
            BroadcastToAll(teamMsg);
        }

        // 添加到玩家列表
        if (!connectedPlayers.Contains(msg.id))
        {
            connectedPlayers.Add(msg.id);
        }

        // 在本地生成玩家
        Color playerColor = new Color(msg.colorR, msg.colorG, msg.colorB);
        Vector3 position = new Vector3(msg.posX, msg.posY, msg.posZ);
        SpawnPlayer(msg.id, playerColor, position);
    }

    // 处理队伍分配消息
    private void HandleTeamAssignMessage(NetworkMessage msg)
    {
        string team = msg.data;
        Debug.Log($"玩家 {msg.id} 被分配到队伍 {team}");

        // 更新玩家颜色
        if (players.TryGetValue(msg.id, out GameObject playerObj))
        {
            Renderer renderer = playerObj.GetComponent<Renderer>();
            if (renderer != null)
            {
                Color teamColor = new Color(msg.colorR, msg.colorG, msg.colorB);
                renderer.material.color = teamColor;
            }
        }
    }

    // 处理游戏开始消息
    private void HandleGameStartMessage(NetworkMessage msg)
    {
        float duration = float.Parse(msg.data);
        Debug.Log($"游戏开始，持续 {duration} 秒");

        // 通知GameManager开始游戏
        gameManager.HandleGameStart(duration);
    }

    // 处理游戏结束消息
    private void HandleGameEndMessage(NetworkMessage msg)
    {
        string[] parts = msg.data.Split(':');
        string winningTeam = parts[0];
        int scoreA = int.Parse(parts[1]);
        int scoreB = int.Parse(parts[2]);

        Debug.Log($"游戏结束，获胜队伍: {winningTeam}，比分 A:{scoreA} - B:{scoreB}");

        // 通知GameManager游戏结束
        gameManager.HandleGameEnd(winningTeam, scoreA, scoreB);
    }

    // 处理分数更新消息
    private void HandleScoreUpdateMessage(NetworkMessage msg)
    {
        string[] parts = msg.data.Split(':');
        string team = parts[0];
        int score = int.Parse(parts[1]);

        Debug.Log($"队伍 {team} 分数更新为 {score}");

        // 更新GameManager中的分数
        GameManager gameManager = GameManager.Instance;
        if (gameManager != null)
        {
            // 更新分数（需要在GameManager中添加方法）
            gameManager.UpdateTeamScore(team, score);
        }
    }

    // 处理断开连接消息
    private void HandleDisconnectMessage(NetworkMessage msg)
    {
        Debug.Log($"玩家断开连接: {msg.id}");

        // 从列表中移除
        if (connectedPlayers.Contains(msg.id))
        {
            connectedPlayers.Remove(msg.id);
        }

        // 通知游戏管理器
        gameManager.HandlePlayerDisconnect(msg.id);

        // 销毁玩家对象
        if (players.TryGetValue(msg.id, out GameObject playerObj))
        {
            Destroy(playerObj);
            players.Remove(msg.id);
        }

        // 如果是服务器，从客户端列表移除
        if (isServer)
        {
            clientEndPoints.Remove(msg.id);
        }
    }

    // 处理移动消息
    private void HandleMoveMessage(NetworkMessage msg)
    {
        if (players.ContainsKey(msg.id) && msg.id != myId)
        {
            Vector3 newPos = new Vector3(msg.posX, msg.posY, msg.posZ);
            float newRotY = msg.rotY;
            GameObject playerObj = players[msg.id];

            // 平滑移动
            StartCoroutine(SmoothMove(playerObj, newPos, 0.1f));

            // 直接同步旋转
            playerObj.transform.rotation = Quaternion.Euler(0, newRotY, 0);

            // 服务器转发移动消息
            if (isServer)
            {
                BroadcastToAll(msg, msg.id); // 不发给源玩家
            }
        }
    }

    // 处理颜色消息
    private void HandleColorMessage(NetworkMessage msg)
    {
        if (players.ContainsKey(msg.id))
        {
            Color newColor = new Color(msg.colorR, msg.colorG, msg.colorB);

            Renderer renderer = players[msg.id].GetComponent<Renderer>();
            if (renderer != null)
            {
                renderer.material.color = newColor;
            }

            // 服务器转发
            if (isServer)
            {
                BroadcastToAll(msg);
            }
        }
    }

    // 处理shoot消息
    private void HandleShootMessage(NetworkMessage msg)
    {
        // 从消息中提取位置和方向
        Vector3 position = new Vector3(msg.posX, msg.posY - 0.8f, msg.posZ);
        Vector3 direction = new Vector3(msg.dirX, msg.dirY, msg.dirZ);

        Debug.Log(position);

        // 实例化炮弹
        SpawnBullet(msg.id, position, direction);

        // 服务器转发
        if (isServer)
        {
            BroadcastToAll(msg);
        }
    }

    // 处理health消息
    private void HandleHealthMessage(NetworkMessage msg)
    {
        if (players.ContainsKey(msg.id))
        {
            PlayerController player = players[msg.id].GetComponent<PlayerController>();
            if (player != null)
            {
                player.health = msg.health;
                // 刷新UI
                player.UpdateHealthUI();
            }
        }
    }

    // 处理击中消息
    private void HandleHitMessage(NetworkMessage msg)
    {
        Debug.Log($"玩家 {msg.targetId} 被 {msg.id} 击中，造成 {msg.damage} 伤害");

        // 如果是服务器，处理伤害并广播
        if (isServer)
        {
            // 查找目标玩家
            if (players.TryGetValue(msg.targetId, out GameObject targetObj))
            {
                PlayerController targetController = targetObj.GetComponent<PlayerController>();
                if (targetController != null)
                {
                    // 扣血
                    targetController.health -= msg.damage;

                    // 广播血量更新
                    NetworkMessage healthMsg = new NetworkMessage
                    {
                        id = msg.targetId,
                        type = "health",
                        health = targetController.health
                    };
                    BroadcastToAll(healthMsg);

                    // 如果玩家死亡
                    if (targetController.health <= 0)
                    {
                        // 通知GameManager处理死亡和计分
                        gameManager.HandlePlayerDeath(msg.targetId, msg.id);
                    }
                }
            }
        }
    }

    // 获取玩家对象
    public PlayerController GetPlayerById(string playerId)
    {
        if (players.TryGetValue(playerId, out GameObject playerObj))
        {
            return playerObj.GetComponent<PlayerController>();
        }
        return null;
    }

    // 平滑移动协程
    System.Collections.IEnumerator SmoothMove(GameObject obj, Vector3 targetPos, float duration)
    {
        Vector3 startPos = obj.transform.position;
        float elapsed = 0;

        while (elapsed < duration)
        {
            obj.transform.position = Vector3.Lerp(startPos, targetPos, elapsed / duration);
            elapsed += Time.deltaTime;
            yield return null;
        }

        obj.transform.position = targetPos;
    }

    // 发送消息给所有人
    public void BroadcastToAll(NetworkMessage msg, string excludeId = "")
    {
        if (!isServer || !isConnected) return;

        string json = JsonUtility.ToJson(msg);
        byte[] data = Encoding.ASCII.GetBytes(json);

        // 广播到所有客户端
        foreach (var client in clientEndPoints)
        {
            // 排除特定ID
            if (excludeId != "" && client.Key == excludeId)
                continue;

            try
            {
                socket.SendTo(data, client.Value);
            }
            catch (Exception e)
            {
                Debug.LogError("发送广播消息失败: " + e.Message);
            }
        }
    }

    // 发送消息(主要接口，接收参数NetworkMessage类，实现信息同步)
    public void SendMessage(NetworkMessage msg)
    {
        if (!isConnected) return;

        string json = JsonUtility.ToJson(msg);
        byte[] data = Encoding.ASCII.GetBytes(json);

        try
        {
            if (isServer)
            {
                // 服务器本地先处理
                UnityMainThreadDispatcher.Instance().Enqueue(() => {
                    switch (msg.type)
                    {
                        case "shoot":
                            HandleShootMessage(msg);
                            break;
                        case "hit":
                            HandleHitMessage(msg);
                            break;
                            // 其他类型...
                    }
                });

                // 再广播给所有客户端
                BroadcastToAll(msg);
            }
            else
            {
                // 客户端发送到服务器
                IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(serverIP), port);
                socket.SendTo(data, serverEndPoint);
            }
        }
        catch (Exception e)
        {
            Debug.LogError("发送消息失败: " + e.Message);
        }
    }

    // 发送消息给特定终端
    public void SendMessageTo(NetworkMessage msg, EndPoint target)
    {
        if (!isConnected) return;

        string json = JsonUtility.ToJson(msg);
        byte[] data = Encoding.ASCII.GetBytes(json);

        try
        {
            socket.SendTo(data, target);
        }
        catch (Exception e)
        {
            Debug.LogError("向特定目标发送消息失败: " + e.Message);
        }
    }

    // 发送移动消息
    public void SendMoveMessage(Vector3 position, float rotY)
    {
        NetworkMessage moveMsg = new NetworkMessage
        {
            id = myId,
            type = "move",
            posX = position.x,
            posY = position.y,
            posZ = position.z,
            rotY = rotY
        };
        SendMessage(moveMsg);
    }

    // 发送颜色变更消息
    public void SendColorMessage(Color color)
    {
        NetworkMessage colorMsg = new NetworkMessage
        {
            id = myId,
            type = "color",
            colorR = color.r,
            colorG = color.g,
            colorB = color.b
        };

        SendMessage(colorMsg);
    }

    public void SendShootMessage(Vector3 position, Vector3 direction)
    {
        print("ssm");
        NetworkMessage shootMsg = new NetworkMessage
        {
            id = myId,
            type = "shoot",
            posX = position.x,
            posY = position.y,
            posZ = position.z,
            dirX = direction.x,
            dirY = direction.y,
            dirZ = direction.z
        };

        SendMessage(shootMsg);
    }

    // 发送击中消息
    public void SendHitMessage(string shooterId, string targetId, float damage)
    {
        NetworkMessage hitMsg = new NetworkMessage
        {
            id = shooterId,
            type = "hit",
            targetId = targetId,
            damage = damage
        };
        SendMessage(hitMsg);
    }

    void OnDestroy()
    {
        DisconnectFromServer();
    }

    void OnApplicationQuit()
    {
        DisconnectFromServer();
    }
}